package org.donhuan.rms.ui.actions;

import org.donghuan.rms.framework.domain.RecordFile;
import org.donghuan.rms.framework.domain.RecordPage;
import org.donhuan.rms.ui.dialogs.CreateProjectDialog;
import org.donhuan.rms.ui.model.ITreeAndWorkbenchAdapter;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;

public class NewRecordPageAction extends Action implements ISelectionListener,
		IWorkbenchAction {
	private static final String ID = "ogr.donghuan.rms.actions.newRecordPageAction";
	private IWorkbenchWindow window;
	private IStructuredSelection selected;

	public NewRecordPageAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&RecordFile");
		setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
				.getImageDescriptor(ISharedImages.IMG_DEF_VIEW));
		window.getSelectionService().addSelectionListener(this);
	}

	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}

	public void selectionChanged(IWorkbenchPart part, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			selection = (IStructuredSelection) selection;
			setEnabled(((IStructuredSelection) selection).size() == 1
					&& ((IStructuredSelection) selection).getFirstElement() instanceof RecordFile);
		} else {
			setEnabled(false);
		}
	}

	@Override
	public void run() {
		CreateProjectDialog dialog = new CreateProjectDialog(window.getShell());
		int code = dialog.open();
		if (code == Window.OK) {
			RecordPage recordPage = new RecordPage(dialog.getText());
			selected = (IStructuredSelection) window.getSelectionService()
					.getSelection();
			ITreeAndWorkbenchAdapter adapter = (ITreeAndWorkbenchAdapter) Platform
					.getAdapterManager().loadAdapter(selected.getFirstElement(),
							ITreeAndWorkbenchAdapter.class.getName());
				adapter.addChild(selected.getFirstElement(),recordPage);

		}
		super.run();
	}

}
